/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.janalise.system;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author boskyn9
 */
public class ManagerFiles {

    private static ManagerFiles instance = new ManagerFiles();
    private String repositorio;
    private List<File> files = new ArrayList<File>();

    public List<File> getFiles() {        
        return files;
    }

    public ManagerFiles() {
        repositorio = Configurar.getInstance().getPathRepositorio();
        carregarFiles(repositorio);
    }

    public static ManagerFiles getInstance() {
        return instance;
    }

    private void carregarFiles(String path) {
        File dir = new File(path);
        if(!dir.exists()){
            try {
                Configurar.getInstance().setRepositorio("");
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ManagerFiles.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ManagerFiles.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            if(!dir.canRead())
                JOptionPane.showMessageDialog(null, "Não é possível ler o diretório! (permissão negada)", "Erro read", JOptionPane.ERROR_MESSAGE);
            else{
                File pdfs[] = dir.listFiles(new PDFFilter());
                for (int i = 0; i < pdfs.length; i++) {
                    File file = pdfs[i];
                    if(!file.isDirectory()){
                        files.add(file);
                    }else{
                        carregarFiles(file.getAbsolutePath());
                    }
                }
            }
        }        
    }
}

class PDFFilter implements FileFilter {

	@Override
	public boolean accept(File f) {
		boolean flag = false;
		String nome = f.getName().toLowerCase();
		if(f.isDirectory())
                    flag = true;
                
                if (f.isFile()) {
			if (!nome.toLowerCase().endsWith(".pdf"))
				flag = false;
			else
                            flag = true;
                }
		return flag;
        }
}